package practice1;

public class LinkListStack {
	private int maxSize;//最大容量
	private int top = -1;//栈顶index
	private Node headNode = new Node(0);//创建头节点
	private Node curNode = headNode;//当前栈顶节点，一开始指向头节点
	
	public int getMaxSize() {
		return maxSize;
	}
	public void setMaxSize(int maxSize) {
		this.maxSize = maxSize;
	}
	public Node getHeadNode() {
		return headNode;
	}
	public void setHeadNode(Node headNode) {
		this.headNode = headNode;
	}
	public boolean isEmpty() {
		return top==-1;
	}
	public boolean isFull() {
		return top == maxSize -1;
	}
	//向栈中添加元素
	public void push(int value) {
		//判断是否栈满，若已满，就返回并提示
		if (isFull()) {
			System.out.println("栈已满！");
			return;
		}
		
		top++;
		Node newNode = new Node(value);//创建一个新节点
		//将新节点加入链表
		curNode.setNext(newNode);
		newNode.setPreNode(curNode);
		//栈顶节点指向新节点
		curNode = newNode;
		
	}
	public int pop() {
		//判断是否栈空，空栈无法出栈
		if (isEmpty()) {
			throw new RuntimeException("栈为空！");
		}
		//用popValue保存栈顶的元素值
		int popValue = curNode.getValue();
		//栈顶指向前一元素
		curNode = curNode.getPreNode();
		//栈顶后节点置为null
		curNode.setNext(null);
		top--;//栈顶的index--
		return popValue;
	}
	public void list() {
		if (isEmpty()) {
			System.out.println("栈为空！");
		}
		//从链表尾倒着读取元素
		Node tempNode = curNode;
		while (tempNode.getPreNode() != null) {
			System.out.print(" "+tempNode.getValue());
			tempNode = tempNode.getPreNode();
		}
		System.out.println("");
	}
}
